/**
Convert2Part.java
This is a simple java program that uses the partition
file from the output of a partitioner and the element
file from the output of the triangle mesh generator to
create a .part (partition file) that is readable by the showme
application.
*/
import java.util.*;
import java.io.*;
public class Convert2Part
{
   public static void main(String args[]) throws FileNotFoundException
   {
      try
      {
         String temp;
         temp = args[0];
         temp = args[1];
         temp = args[2];
      }
      catch(ArrayIndexOutOfBoundsException o)
      {
         System.out.println("Usage: java Convert2Part <partition file> <element file> <#Partitions>");
         System.exit(0);
      }
      Scanner part = new Scanner(new File(args[0]));
      Scanner element = new Scanner(new File(args[1]));
      int end = args[1].indexOf(".ele");
      if(end == -1)
      {
         System.out.println("Element file must have .ele extension");
         System.exit(0);
      }
      String fName = args[1].substring(0,end); //find the name of the element file up to the .ele extension
      PrintStream out = new PrintStream(new File(fName+".part")); //name the part file the same, showme will look for this
      
      int numElements = Integer.parseInt(element.next());
      int numPartitions = Integer.parseInt(args[2]);
      int borderPartition = numPartitions+1;
      out.println(numElements+" "+borderPartition);
      element.next();
      element.next();
   
      //Read in partition data
      ArrayList<Integer> partitions = new ArrayList<Integer>(); //Each index represents a node, its value, the nodes partition
      partitions.add(-1); //Add junk for the first value in arraylist because node numberings start at index 1
      while(part.hasNext())
      {
         partitions.add(part.nextInt());
      }


      //Assign Partitions
      int part2,one,two,three,eleNum;
      String done;
      while(element.hasNext())
      {
         done = element.next(); //Done will be the first thing we read in on a new line, if it is a '#' we break, otherwise, it will be our element number
         if(done.equals("#")) break;
         eleNum = Integer.parseInt(done);
         one = element.nextInt();
         two = element.nextInt();
         three = element.nextInt();
         part2 = partitions.get(two); 
         if(partitions.get(one) == part2 && partitions.get(three) == part2) //If all three nodes of an element are in one partition
         {
            out.println(eleNum+" "+(part2+1)); //Assign the element to the partition
         }
         else
         {
            out.println(eleNum+" "+borderPartition); //Assign the element to the "ghost" partition
         }
      }  
      out.close();
      element.close();
      part.close();
  
   }
}
